import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyPage.dart';

import '../../../Util/HttpGo.dart';
import '../../../Widget/MyInput.dart';

class ClassChangeConfirm extends StatefulWidget {
  dynamic fromOrder;
  dynamic toLesson;
  int fromLessonCount;

  Function() onChangeDone;

  ClassChangeConfirm({required this.fromOrder, required this.toLesson, required this.fromLessonCount, required this.onChangeDone}) {
    if (fromLessonCount < 1) fromLessonCount = 1;
    if (fromLessonCount > fromOrder["lessonTotalCount"]) fromLessonCount = fromOrder["lessonTotalCount"];
  }

  @override
  State<StatefulWidget> createState() {
    return _ClassChangeConfirm();
  }
}

class _ClassChangeConfirm extends State<ClassChangeConfirm> {
  bool agree = false;
  String PayType = "信用卡";

  choosePay() {
    showWheelDialog(context, "", ["信用卡"], (index) {});
  }

  subCount() {
    widget.fromLessonCount -= 1;
    if (widget.fromLessonCount < 1) widget.fromLessonCount = 1;
    getDetail();
    setState(() {});
  }

  addCount() {
    widget.fromLessonCount += 1;
    if (widget.fromLessonCount > sourceLessonObject["remainLessonQty"]) widget.fromLessonCount = sourceLessonObject["remainLessonQty"];
    getDetail();
    setState(() {});
  }

  int type = -1;
  dynamic sourceLessonObject;
  dynamic targetLessonObject;
  dynamic noNeedFeeObject;
  dynamic needFeeObject;
  dynamic feeObject;
  bool selectNoNeed = true;

  getDetail() {
    HttpGo(context).post("/Lesson/GetChangeLessonDetail", {
      "fromPurchaseOrderId": widget.fromOrder["purchaseOrderId"],
      "toLessonId": widget.toLesson["lessonId"],
      "fromLessonCount": widget.fromLessonCount
    }, (data) {
      type = data["type"];
      sourceLessonObject = data["sourceLessonObject"];
      targetLessonObject = data["targetLessonObject"];
      noNeedFeeObject = targetLessonObject["noNeedFeeObject"];
      needFeeObject = targetLessonObject["needFeeObject"];
      selectNoNeed = true;
      setState(() {});
    }, (code, error) => showToast(error));
  }

  String changeRule = "";

  getChangeRule() {
    HttpGo(context).get("/Lesson/GetChangeLessonRegulation", {}, (data) {
      changeRule = data["regulation"];
    }, (code, error) => showToast(error));
  }

  String getCompleteChangeRule() {
    String completeChangeRule = changeRule;
    completeChangeRule = completeChangeRule.replaceAll("{FROM_LO_NAM}", "${sourceLessonObject["lessonName"]}");
    completeChangeRule = completeChangeRule.replaceAll("{FROM_CLS_TIM}", "${sourceLessonObject["lessonTime"]}");
    completeChangeRule = completeChangeRule.replaceAll("{FROM_CLS_CNT}", widget.fromLessonCount.toString());
    completeChangeRule = completeChangeRule.replaceAll("{TO_LO_NAM}", "${targetLessonObject["lessonName"]}");
    completeChangeRule = completeChangeRule.replaceAll("{TO_CLS_TIM}", "${targetLessonObject["lessonTime"]}");
    int toLessonCount = 0;
    if (type == 0) {
      //0 = 1換1
      toLessonCount = widget.fromLessonCount;
    } else if (type == 1) {
      toLessonCount = feeObject["canChangeQty"] ?? -1;
    }
    completeChangeRule = completeChangeRule.replaceAll("{TO_CLS_CNT}", toLessonCount.toString());
    return completeChangeRule;
  }

  confirmChange() {
    if (!agree) {
      showToast("請閱讀並同意換課規章");
      return;
    }
    int toLessonCount = -1;
    if (type == 0) {
      //0 = 1換1
      toLessonCount = widget.fromLessonCount;
    } else if (type == 1) {
      toLessonCount = feeObject["canChangeQty"] ?? -1;
    }
    if (toLessonCount == -1) {
      showToast("toLessonCount == -1");
      return;
    }

    HttpGo(context).post("/Lesson/ChangeLesson", {
      "fromPurchaseOrderId": widget.fromOrder["purchaseOrderId"],
      "toLessonId": widget.toLesson["lessonId"],
      "fromLessonCount": widget.fromLessonCount,
      "toLessonCount": toLessonCount,
    }, (data) {
      if (data["payUrl"] != null) {
        PageUtil().launchURL(data["payUrl"]);
      }
      widget.onChangeDone.call();
      PageUtil().back(context);
    }, (code, error) => showToast(error));
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getDetail();
      getChangeRule();
    });
    super.initState();
  }

  // TextEditingController controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // controller.text = widget.fromLessonCount.toString();
    String oldExpireDate = "";
    String newExpireDate = "";
    if (type >= 0) {
      oldExpireDate = getStrTime(getTimeByUtc(sourceLessonObject["expireDate"]), DateUtil.YMD);
      newExpireDate = getStrTime(getTimeByUtc(targetLessonObject["expireDate"]), DateUtil.YMD);
      feeObject = selectNoNeed ? noNeedFeeObject : needFeeObject;
      feeObject = feeObject ?? {};
    }

    return MyPage(
        "換課",
        type >= 0
            ? Container(
                padding: EdgeInsets.only(bottom: 16),
                child: Column(children: [
                  ///原課程
                  Container(
                      margin: EdgeInsets.fromLTRB(0, 8, 0, 8),
                      padding: EdgeInsets.all(12),
                      color: MyColor.White,
                      child:
                          Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
                        Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                          Text("#${sourceLessonObject["purchaseOrderId"]}",
                              style: TextStyle(fontSize: 12, color: MyColor.Blue, fontWeight: FontWeight.bold)),
                          Text("$oldExpireDate", style: TextStyle(fontSize: 12, color: MyColor.C9)),
                        ]),
                        Text("${sourceLessonObject["displayLessonName"]}", style: TextStyle(fontSize: 15, height: 2, color: MyColor.Blue)),
                        Row(children: [
                          Text("剩餘堂數：${sourceLessonObject["remainLessonQty"]}", style: TextStyle(fontSize: 13, color: MyColor.C7D)),
                          Container(width: 44),
                          Text("欲更換的堂數：", style: TextStyle(fontSize: 13, color: MyColor.C7D)),
                          LocalImage("ic_change_lesson_sub.png", width: 20, height: 20, padding: EdgeInsets.all(8), onTap: subCount),
                          Text("${widget.fromLessonCount}"),
                          // Container(
                          //     height: 28,
                          //     width: 52,
                          //     padding: EdgeInsets.fromLTRB(4, 0, 4, 0),
                          //     decoration: BoxDecoration(
                          //         color: Colors.white,
                          //         borderRadius: BorderRadius.all(Radius.circular(4)),
                          //         border: Border.all(width: 1, color: MyColor.C9)),
                          //     child: NormalInput(inputType: NormalInput.Number, controller: controller, fontColor: MyColor.C7D)),
                          LocalImage("ic_change_lesson_add.png", width: 20, height: 20, padding: EdgeInsets.all(8), onTap: addCount),
                        ]),
                        Visibility(
                            visible: type == 1,
                            child: Align(
                                alignment: Alignment.centerRight,
                                child: Text("${sourceLessonObject["totalAmount"]} 元",
                                    style: TextStyle(fontSize: 13, color: MyColor.Orange, fontWeight: FontWeight.bold))))
                      ])),

                  LocalImage("ic_change_lesson_arrow.png", height: 60),

                  ///新課程
                  Container(
                      padding: EdgeInsets.all(12),
                      color: Color(0xffffeade),
                      child:
                          Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
                        Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                          Text("New", style: TextStyle(fontSize: 13, color: MyColor.Red, fontWeight: FontWeight.bold)),
                          Text("$newExpireDate", style: TextStyle(fontSize: 12, color: MyColor.C9)),
                        ]),
                        Text("${targetLessonObject["displayLessonName"]}", style: TextStyle(fontSize: 15, height: 2, color: MyColor.Blue)),
                        Row(children: [
                          Text("可更換堂數：", style: TextStyle(fontSize: 13, height: 1.5, color: MyColor.C7D)),
                          Visibility(
                              visible: type == 0,
                              child: Text("${widget.fromLessonCount}", style: TextStyle(fontSize: 13, height: 1.5, color: MyColor.C7D))),
                          Visibility(
                              visible: type == 1 && noNeedFeeObject != null,
                              child: TextButton(
                                "${noNeedFeeObject == null ? "" : noNeedFeeObject["canChangeQty"]}堂課",
                                selected: selectNoNeed,
                                onTap: () {
                                  selectNoNeed = true;
                                  setState(() {});
                                },
                              )),
                          Visibility(
                              visible: type == 1 && needFeeObject != null,
                              child: TextButton(
                                "${needFeeObject == null ? "" : needFeeObject["canChangeQty"]}堂課",
                                selected: !selectNoNeed,
                                onTap: () {
                                  selectNoNeed = false;
                                  setState(() {});
                                },
                              ))
                        ]),
                        Visibility(
                            visible: type == 1,
                            child: Align(
                                alignment: Alignment.centerRight,
                                child: Text("${feeObject["totalAmount"]} 元",
                                    style: TextStyle(fontSize: 13, color: MyColor.Orange, fontWeight: FontWeight.bold))))
                      ])),
                  Expanded(
                      child: type == 1
                          ? Container(
                              padding: EdgeInsets.fromLTRB(0, 16, 8, 0),
                              child: Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
                                Text("您的剩餘點數：${feeObject["remainPoint"]}點，使用${feeObject["usePoint"]}點",
                                    style: TextStyle(fontSize: 13, height: 2, color: MyColor.C7D)),
                                Text("仍需付費：${feeObject["payPrice"]}元", style: TextStyle(fontSize: 13, height: 2, color: MyColor.C7D)),
                                Container(height: 8),
                                feeObject["payPrice"] == 0
                                    ? Container()
                                    : Container(width: 100, child: ChooserBox(PayType, onTap: choosePay))
                              ]))
                          : Container()),
                  Row(mainAxisSize: MainAxisSize.min, children: [
                    GestureDetector(
                        onTap: () {
                          agree = !agree;
                          setState(() {});
                        },
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                            margin: EdgeInsets.all(8),
                            height: 17,
                            width: 17,
                            decoration: Global.getBg(agree ? MyColor.Orange : Color(0xffccd1d3), 10),
                            child: agree ? LocalImage("check.png", padding: EdgeInsets.all(1)) : Container())),
                    Text("我同意", style: TextStyle(color: MyColor.C7D)),
                    TextBtn("換課規章", style: TextStyle(color: MyColor.Blue), onTap: () {
                      showWidgetDialog(context, ClassChangeTerm(getCompleteChangeRule()));
                    }),
                    Text("。", style: TextStyle(color: MyColor.C7D))
                  ]),
                  Container(height: 1, color: Color(0xffdee2e6), margin: EdgeInsets.fromLTRB(0, 8, 0, 16)),
                  Row(mainAxisSize: MainAxisSize.min, children: [
                    TextBtn("取消", height: 36, width: 100, style: TextStyle(color: MyColor.Orange), onTap: () {
                      PageUtil().back(context);
                    }),
                    Button("確認換課", height: 36, bgColor: MyColor.Orange, width: 120, radius: 4, onTap: confirmChange)
                  ])
                ]))
            : Container(),
        bgColor: MyColor.F8);
  }
}

class TextButton extends StatelessWidget {
  String text;
  bool selected;
  Function() onTap;

  TextButton(this.text, {required this.onTap, this.selected = false});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: onTap,
        child: Container(
            margin: EdgeInsets.only(left: 8),
            padding: EdgeInsets.symmetric(horizontal: 6),
            decoration: Global.getBorderBg(selected ? MyColor.Orange : MyColor.A0, 4),
            child: Text(text, style: TextStyle(color: selected ? MyColor.Orange : MyColor.A0))));
  }
}

class ClassChangeTerm extends StatelessWidget {
  String term;

  ClassChangeTerm(this.term);

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: Global.getWhiteBg(8),
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            Container(
                height: 40,
                color: MyColor.Orange,
                alignment: Alignment.center,
                child: Text("課程轉換規範", style: TextStyle(fontSize: 22, color: MyColor.White, fontWeight: FontWeight.bold))),
            Container(height: 12),
            Expanded(
                child: SingleChildScrollView(
              child: Text(term, style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 2)),
              // child: RichText(
              //   text: TextSpan(text: term, style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 2), children: [
              //     TextSpan(text: "轉換前課程為：課程名稱：", style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 2)),
              //     TextSpan(text: "留學準備套裝課程Level3-7", style: TextStyle(fontSize: 14, color: MyColor.BlueTxt, height: 2)),
              //     TextSpan(text: "，", style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 2)),
              //     TextSpan(text: "50", style: TextStyle(fontSize: 14, color: MyColor.BlueTxt, height: 2)),
              //     TextSpan(text: "分鐘，共", style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 2)),
              //     TextSpan(text: "66", style: TextStyle(fontSize: 14, color: MyColor.BlueTxt, height: 2)),
              //     TextSpan(text: "堂\n轉面後課程為：課程名稱：", style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 2)),
              //     TextSpan(text: "高級實英Level8-9", style: TextStyle(fontSize: 14, color: MyColor.BlueTxt, height: 2)),
              //     TextSpan(text: "，", style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 2)),
              //     TextSpan(text: "50", style: TextStyle(fontSize: 14, color: MyColor.BlueTxt, height: 2)),
              //     TextSpan(text: "分鐘，共", style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 2)),
              //     TextSpan(text: "22", style: TextStyle(fontSize: 14, color: MyColor.BlueTxt, height: 2)),
              //     TextSpan(text: "堂", style: TextStyle(fontSize: 14, color: MyColor.C7D, height: 2)),
              //   ]),
              // ),
            )),
            Container(height: 12),
            Button("確認", width: 72, height: 32, bgColor: MyColor.Orange, onTap: () {
              PageUtil().back(context);
            })
          ],
        ));
  }
}
